import React, { useMemo } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import * as PensionCalc from '../utils/pensionCalculations.js';
import { formatCurrency, formatPercentage, formatYears, createTooltipFormatter } from '../utils/chartUtils.jsx';

/**
 * 工资-月养老金关系图
 * @param {Object} props - 组件属性
 * @param {number} props.contributionYears - 缴费年限
 * @param {number} props.localAverageSalary - 当地上年度在岗职工月平均工资
 * @param {number} props.retirementAge - 退休年龄
 * @param {string} props.employmentType - 就业类型（在职/灵活）
 * @param {number} props.baseRate - 灵活就业基准比例
 * @returns {JSX.Element}
 */
const PensionBySalaryChart = ({ 
  contributionYears, 
  localAverageSalary, 
  retirementAge, 
  employmentType,
  baseRate
}) => {
  const data = useMemo(() => {
    // 只针对在职人员有效，灵活就业人员的养老金不直接与当前工资相关
    if (employmentType !== 'employee') {
      return []; // 灵活就业人员返回空数据
    }

    const chartData = [];
    const payoutMonths = PensionCalc.getPayoutMonths(retirementAge);
    const minSalary = Math.floor(localAverageSalary * 0.6); // 最低工资为当地平均工资的60%
    const maxSalary = Math.ceil(localAverageSalary * 3); // 最高工资为当地平均工资的300%
    const step = Math.round((maxSalary - minSalary) / 20); // 分20个点
    
    for (let salary = minSalary; salary <= maxSalary; salary += step) {
      // 计算在职人员各项指标
      const contributionIndex = PensionCalc.calculateContributionIndex(salary, localAverageSalary);
      const personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(localAverageSalary, contributionIndex);
      const personalAccountTotal = PensionCalc.calculateEmployeePAT(salary, 0.08, contributionYears);
      const totalContribution = PensionCalc.calculateEmployeeTotalContribution(salary, 0.08, contributionYears);
      
      // 计算养老金
      const basicPension = PensionCalc.calculateBasicPension(localAverageSalary, personalIndexedSalary, contributionYears);
      const personalAccountPension = PensionCalc.calculatePersonalAccountPension(personalAccountTotal, payoutMonths);
      const monthlyPension = PensionCalc.calculateMonthlyPension(basicPension, personalAccountPension);
      
      // 计算收支平衡点
      const breakEvenPoint = PensionCalc.findBreakEvenPoint(totalContribution, monthlyPension);
      
      chartData.push({
        salary,
        monthlyPension,
        basicPension,
        personalAccountPension,
        totalContribution,
        breakEvenPoint,
        contributionIndex
      });
    }
    
    return chartData;
  }, [contributionYears, localAverageSalary, retirementAge, employmentType, baseRate]);

  // 使用通用tooltip格式化器
  const CustomTooltip = createTooltipFormatter({
    formatLabel: (label) => `税前工资: ${formatCurrency(label, false)}`,
    formatters: {
      monthlyPension: (value) => formatCurrency(value),
      basicPension: (value) => formatCurrency(value),
      personalAccountPension: (value) => formatCurrency(value),
      totalContribution: (value) => formatCurrency(value, false),
      breakEvenPoint: (value) => formatYears(value),
      contributionIndex: (value) => formatPercentage(value, 2)
    },
    nameMap: {
      monthlyPension: '月养老金',
      basicPension: '基础养老金',
      personalAccountPension: '个人账户养老金',
      totalContribution: '个人缴费总额',
      breakEvenPoint: '收支平衡点',
      contributionIndex: '缴费指数'
    }
  });
  
  // 如果是灵活就业人员，显示提示信息
  if (employmentType !== 'employee') {
    return (
      <div className="chart-container">
        <h3>工资-月基本养老金关系图</h3>
        <div className="chart-note">
          注：灵活就业人员的养老金与当前工资无直接关系，而是与所选基准档次相关。请使用缴费年限图表查看养老金变化。
        </div>
      </div>
    );
  }

  return (
    <div className="chart-container">
      <h3>工资-月基本养老金关系图</h3>
      <p className="chart-description">
        本图表展示不同税前工资水平下的月养老金变化趋势。紫色线表示月基本养老金总额，绿色线表示基础养老金部分，
        黄色线表示个人账户养老金部分，橙色线表示缴费指数。您可以从图表看出工资增长如何影响您的养老金构成和总额，
        以及养老金增长与工资增长之间的关系。工资范围从当地平均工资的60%到300%。
      </p>
      <ResponsiveContainer width="100%" height={400}>
        <LineChart
          data={data}
          margin={{
            top: 20,
            right: 30,
            left: 20,
            bottom: 10,
          }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis 
            dataKey="salary" 
            label={{ value: '税前工资（元/月）', position: 'insideBottomRight', offset: -5 }} 
            tickFormatter={(value) => formatCurrency(value, false)}
          />
          <YAxis 
            yAxisId="left"
            label={{ value: '月基本养老金（元）', angle: -90, position: 'insideLeft' }}
            tickFormatter={(value) => formatCurrency(value, false)}
          />
          <YAxis 
            yAxisId={1}
            orientation="right"
            domain={[0, 3]}
            tickFormatter={(value) => formatPercentage(value)}
            label={{ value: '缴费指数', angle: 90, position: 'insideRight' }}
          />
          <Tooltip content={<CustomTooltip />} />
          <Legend />
          <Line 
            type="monotone" 
            dataKey="monthlyPension" 
            name="月基本养老金" 
            stroke="#8884d8" 
            activeDot={{ r: 8 }} 
            yAxisId="left"
          />
          <Line 
            type="monotone" 
            dataKey="basicPension" 
            name="基础养老金" 
            stroke="#82ca9d" 
            yAxisId="left"
          />
          <Line 
            type="monotone" 
            dataKey="personalAccountPension" 
            name="个人账户养老金" 
            stroke="#ffc658" 
            yAxisId="left"
          />
          <Line 
            type="monotone" 
            dataKey="contributionIndex" 
            name="缴费指数" 
            stroke="#ff7300" 
            yAxisId={1}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
};

export default PensionBySalaryChart; 